<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <el-tab-pane label="按日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="echartsClick" title="按日统计趋势"/>
            </el-col>
          </el-tab-pane>
          <!-- <el-tab-pane label="按所在分区统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="按所在分区统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="按所在校区统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie2Data" @pieclick="echartsClick" title="按所在校区统计分析"/>
            </el-col>
          </el-tab-pane> -->
          <el-tab-pane label="按资产名称统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按资产名称统计分析"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按事件类型统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie4Data" @pieclick="echartsClick" title="按事件类型统计分析"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按严重性等级统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie5Data" @pieclick="echartsClick" title="按严重性等级统计分析"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <!-- <el-table-column label="所在分区" show-overflow-tooltip prop="PrimArea" width="150" align="left">
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
          <el-table-column label="所在校区" show-overflow-tooltip prop="SchoolName" align="left">
            <template slot-scope="{row}">
              <span>{{ row.SchoolName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" align="left">
            <template slot-scope="{row}">
              <span>{{ row.DeviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发生时间" show-overflow-tooltip prop="TransTime" width="160px" align="left"></el-table-column>
          <el-table-column label="事件类型" show-overflow-tooltip prop="EventID" align="left">
            <template slot-scope="{row}">
              {{ getEventLabel(row.EventID) }}({{ row.EventID }})
            </template>
          </el-table-column>
          <el-table-column label="发生事件源" show-overflow-tooltip prop="EventType" width="100" align="left">
            <template slot-scope="{row}">
              <span v-show="row.EventType == '1'">管理中心</span>
              <span v-show="row.EventType == '2'">校区装置</span>
              <span v-show="row.EventType == '3'">终端资产</span>
            </template>
          </el-table-column>
          <el-table-column label="严重性等级" show-overflow-tooltip prop="EventLevel" width="100" align="left">
            <template slot-scope="{row}">
              <span style="color:#F56C6C" v-show="row.EventLevel == '1'">紧急</span>
              <span style="color:#E6A23C" v-show="row.EventLevel == '2'">重要</span>
              <span style="color:#909399" v-show="row.EventLevel == '3'">默认</span>
              <span style="color:#409EFF" v-show="row.EventLevel == '4'">普通</span>
              <span style="color:#67C23A" v-show="row.EventLevel == '5'">告知</span>
            </template>
          </el-table-column>
          <el-table-column label="描述信息" show-overflow-tooltip prop="Descp" align="left"></el-table-column>
          <el-table-column label="确认状态" show-overflow-tooltip prop="IsAck" width="100" align="left">
            <template slot-scope="{row}">
              <span style="color:#909399" v-show="row.IsACK == '0'">未确认</span>
              <span style="color:#67C23A" v-show="row.IsACK == '1'">已确认</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="120px" fixed="right">
            <template slot="header" slot-scope="scope">
              <el-button size="mini" :type="!confirmThisPage ? 'info' : 'primary'" :disabled="!confirmThisPage" @click="changeMailGlobalAll(scope.row)">确认本页</el-button>
            </template> 
            <template slot-scope="scope">
              <el-button size="mini" :type="scope.row.IsACK == '1' ? 'info' : 'primary'" :disabled="scope.row.IsACK == '1'" @click="changeMailGlobal(scope.row)">确  认</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { getNowDay, parseTime, formatTime, formatTime2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
export default {
  components: { connsearch, barchart, piechart },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按日统计趋势',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      confirmThisPage: false,
      barchartData: {xAxis:[],series:[]},
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      pie5Data: [],
      tableData:[],
      eventList: [],
      searchform:{},
      options:{},
      searchobj: {},
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "严重性等级", // label文字
          prop: "EventLevel", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择等级", // elementui组件属性
          options: [
            { label: '紧急', value: 1 },
            { label: '重要', value: 2 },
            { label: '默认', value: 3 },
            { label: '普通', value: 4 },
            { label: '告知', value: 5 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.EventLevel = val
            },
          },
        },
        {
          col: 6,
          hidden: false,
          label: "事件类型", // label文字
          prop: "EventID", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择事件类型", // elementui组件属性
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.EventID = val
            },
          },
        },
        {
          col: 6,
          label: "描述信息", // label文字
          prop: "Descp", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入描述信息,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Descp = val
            },
          },
        },
        {
          col: 8,
          label: "资产选择",
          prop:"DeviceName",
          element: "el-select",
          initValue: "",
          placeholder: "请选择资产",
          options:[],
          events: {
            input(val) {
              that.searchform.DeviceName = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "确认状态", // label文字
          prop: "IsAck", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择等级", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '未确认', value: 1 },
            { label: '已默认', value: 2 },
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.IsAck = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'IsAck', 0)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.GetParamDictEvent()
    // this.GetDeviceStatusSumTree()
    this.CenterGetDevice()
  },
  methods: {
    async CenterGetDevice(){
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000000
        },
        Filter:{
          Status: 0,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let assetList = []
      res.Data.map(item => {
        assetList.push({ label: item.DeviceName, value: item.DeviceID })
      })
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = assetList
        }
      })
    },
    // 获取子节点的资产
    async lazyLoad(node, resolve){
      if(node.level < 4){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SchoolName: node.label,
          }
        }
        const res = await connrequest('CenterGetDevice', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.DeviceName, value: item.DeviceName, level: 5, children: undefined} )
        })
        resolve(arr) 
      }
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
              children: secondArea.School.map(School => ({
                SubClass: School.SchoolName,
                level: 4,
              }))
          }))
        }))
      }
    },
    // 获取资产树
    async GetDeviceStatusSumTree() {
      const res = await connrequest('GetDeviceStatusSumTree')
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = [this.transformData(res.Data)]
        }
      })
    },
    // 获取事件定义
    async GetParamDictEvent(){
      const res = await connrequest('GetParamDictEvent')
      let arr = []
      res.Data.map(item => {
        arr.push({label: item.AlarmDescp, value: item.EventID})
      })
      this.formOptions.map( item => {
        if(item.label === '事件类型'){
          item.options = arr
          item.initValue = arr[0]?.value
        }
      })
      this.eventList = arr
    },
    getEventLabel(eventID) {
      return this.eventList.find(item => item.value === eventID)?.label || null;
    },
    async changeMailGlobal(row){
      const data = {
        Data: [row.AutoID]
      }
      const res = await connrequest('ConfirmEvent', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('确认成功')
        this.getData()
      }
    },
    async changeMailGlobalAll(){
      const arr = this.tableData.map(item => item.AutoID);
      const data = {
        Data: arr
      }
      const res = await connrequest('ConfirmEvent', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('确认成功')
        this.getData()
      }
    },
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '按日统计趋势':
          this.GetEventLogSumGroupByDate()
          break;
        case '按所在分区统计分析':
          this.GetEventLogSumGroupByArea()
          break;
        case '按所在校区统计分析':
          this.GetEventLogSumGroupBySchool()
          break;
        case '按资产名称统计分析':
          this.GetEventLogSumGroupByDevice()
          break;
        case '按事件类型统计分析':
          this.GetEventLogSumGroupByEventID()
          break;
        default:
          this.GetEventLogSumGroupByLevel()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '按日统计趋势'){
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog(this.searchobj)
      }else if(title === '按所在分区统计分析'){
        this.searchobj = { PrimArea: val.split('_')[0], SecondArea: val.split('_')[1] }
        this.GetEventLog(this.searchobj)
      }else if(title === '按所在校区统计分析'){
        this.searchobj = { SchoolName: val }
        this.GetEventLog(this.searchobj)
      }else if(title === '按资产名称统计分析'){
        this.searchobj = { DeviceName: val }
        this.GetEventLog(this.searchobj)
      }else if(title === '按事件类型统计分析'){
        const eventListObject = Object.fromEntries(this.eventList.map(item => [item.label, item.value]));
        this.searchobj = { EventID: eventListObject[val] }
        this.GetEventLog(this.searchobj)
      }else{
        let EventLevel = {紧急: 1, 重要: 2, 默认: 3, 普通: 4, 告知: 5 }
        // this.searchobj = { Level: EventLevel[val] }
        this.searchobj = { Level: 'NULL' }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计趋势':
          this.GetEventLogSumGroupByDate()
          break;
        case '按所在分区统计分析':
          this.GetEventLogSumGroupByArea()
          break;
        case '按所在校区统计分析':
          this.GetEventLogSumGroupBySchool()
          break;
        case '按资产名称统计分析':
          this.GetEventLogSumGroupByDevice()
          break;
        case '按事件类型统计分析':
          this.GetEventLogSumGroupByEventID()
          break;
        default:
          this.GetEventLogSumGroupByLevel()
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetEventLog', data)
      res.Data = res.Data || []
      this.confirmThisPage = false
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        // 如果存在未确认的数据，确认本页按钮显示可用
        if(item.IsACK === 0){
          this.confirmThisPage = true
        }
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 获取事件日期统计
    async GetEventLogSumGroupByDate(){
      let xAxis = []
      let t1 = []
      let t2 = []
      let t3 = []
      let t4 = []
      let t5 = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.TransDate)
        t1.push(item[1])
        t2.push(item[2])
        t3.push(item[3])
        t4.push(item[4])
        t5.push(item[5])
      })
      this.barchartData = {xAxis, t1, t2, t3, t4, t5}
    },
    // 按所在分区统计分析
    async GetEventLogSumGroupByArea(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetEventLogSumGroupByArea', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 按所在校区统计分析
    async GetEventLogSumGroupBySchool(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetEventLogSumGroupBySchool', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie2Data = arr
    },
    // 按事件资产统计分析
    async GetEventLogSumGroupByDevice(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDevice', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie3Data = arr
    },
    // 按事件类型统计分析
    async GetEventLogSumGroupByEventID(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetEventLogSumGroupByEventID', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: this.getEventLabel(item.ClassID) || '未知', value: item.Count})
      })
      this.pie4Data = arr
    },
    // 按严重性等级统计分析
    async GetEventLogSumGroupByLevel(){
      let EventLevel = ['紧急', '重要', '默认', '普通', '告知']
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceID: this.searchform.DeviceName,
          Level:this.searchform.EventLevel,
          EventID:this.searchform.EventID,
          IsAck:this.searchform.IsAck,
          Descp: this.searchform.Descp || '',
        }
      }
      const res = await connrequest('GetEventLogSumGroupByLevel', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: EventLevel[item.ClassID - 1] || '未知', value: item.Count})
      })
      this.pie5Data = arr
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      // this.searchobj = {}
      this.searchform = {...val}
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "确认状态"){
          item.initValue = 0
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'IsAck', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      console.log(this.searchobj);
      console.log(this.searchform);
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleCurrentChange( pageNum ){
      console.log(this.searchobj);
      console.log(this.searchform,2222222);
      this.pageNum = pageNum
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>